package com.qipay.sp.impl;

import com.qipay.baas.model.SpConfig;
import com.qipay.mapper.SpConfigMapper;
import com.qipay.sp.SpConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpConfigServiceImpl implements SpConfigService {

    @Autowired
    SpConfigMapper spConfigMapper;

    @Override
    public Map<String, Object> getKeyValues(Long spid) {
        List<SpConfig> spConfigs = spConfigMapper.getKeyValues(spid);
        if(spConfigs == null || spConfigs.size() == 0)
            return new HashMap<>();

        Map<String, Object> result = new HashMap<>(spConfigs.size());
        spConfigs.forEach(p-> result.put(p.getKey(), p.getVal()));
        return result;
    }

    @Override
    public String getValue(Long spid, String key) {
        SpConfig spConfig = spConfigMapper.getValue(spid, key);
        if (spConfig == null)
            return null;

        return spConfig.getVal();
    }

    @Override
    @Transactional
    public int insert(SpConfig sp) {
        return spConfigMapper.insert(sp);
    }

    @Override
    @Transactional
    public int update(SpConfig sp) {
        return spConfigMapper.updateByPrimaryKey(sp);
    }

    @Override
    @Transactional
    public int delete(int id) {
        return spConfigMapper.deleteByPrimaryKey((long)id);
    }

    @Override
    public SpConfig get(int id) {
        return spConfigMapper.selectByPrimaryKey((long)id);
    }

    @Override
    public List<SpConfig> getBySpId(Long spid) {
        return spConfigMapper.getKeyValues(spid);
    }

    @Override
    @Transactional
    public int deleteParam() {
        spConfigMapper.deletePddParam("access_token");
        spConfigMapper.deletePddParam("address");
        spConfigMapper.deletePddParam("pdd_uin");
        return spConfigMapper.deletePddParam("pdd_uid");
    }
}
